/* Copyright 2014 Jan Wolter */

/* Comparision function for stack order normalization in currstate() */
static int cmpstacks(const void *p1, const void *p2)
{
    const Stack *s1= *(const Stack **)p1;
    const Stack *s2= *(const Stack **)p2;
    if (s1->n == 0 || s2->n == 0)
	return s2->n - s1->n;
    int c1= s1->c[0] - deck;
    int c2= s2->c[0] - deck;
    return c2 - c1;
}

/* Return a string that uniquely describes the current state. */
char *currstate()
{
    /* ncards for all the cards on things
     * 12 for list terminators.
     */
    char buf[ncard+30], *p= buf;

    /* List of cards on each tableau pile */
#ifdef SORT
    /* We normalize the order of the tableau piles, sorting them by the
     * first card on them. Very helpful for Indefatigable.
     */
    Stack *norm[12];
    for (int k= 0; k < nbitableau; k++)
	norm[k]= stacks + bitableau[k].id;
    /* This seg faults for some reason */
    qsort(norm, nbitableau, sizeof(Stack *), cmpstacks);

    for (int k= 0; k < nbitableau; k++)
    {
	Stack *s= norm[k];
	for (int i= 0; i < s->n; i++)
	    *(p++)= (s->c[i] - deck) + 1;
	*(p++)= ncard + 1; /* The card list terminator */
    }
#else
    /* Non-normalized case */
    for (int k= 0; k < nbitableau; k++)
    {
	Stack *s= stacks + bitableau[k].id;
	for (int i= 0; i < s->n; i++)
	    *(p++)= (s->c[i] - deck) + 1;
	*(p++)= ncard + 1; /* The card list terminator */
    }
#endif
    *p= '\0';

    return strdup(buf);
}
